package com.moyu.crowdsource.service;

import com.aliyun.oss.OSSClient;
import com.moyu.crowdsource.entity.CommodityImage;
import com.moyu.crowdsource.mapperdao.CommodityImageMapper;
import com.moyu.crowdsource.util.MyUUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URL;
import java.util.Date;

@Service
public class OSSService {

  @Autowired CommodityImageService commodityImageService;

  @Value("${oss.endpoint}")
  private String endpoint;

  @Value("${oss.access-key-id}")
  private String accessKeyId;

  @Value("${oss.access-key-secret}")
  private String accessKeySecret;

  @Value("${oss.bucket-name}")
  private String bucketName;

  @Value("${oss.firstkey}")
  private String firstkey;

  @Value("${oss.urlhead}")
  private String urlhead;

  @Value("${oss.access-key-id}")
  private String test;
  // https://moyu-storage.oss-cn-qingdao.aliyuncs.com/images/e0d025c2a34e41e48a6853081d16e7286450351863266548483.jpg?x-oss-process=style/moyustyle

  public void uploadFiled(File file, String filename, CommodityImage commodityImage) {

    // 创建OSSClient实例。
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    // 上传文件。

    ossClient.putObject(bucketName, firstkey + filename, file);
    // 关闭Client。
    ossClient.shutdown();

  }

  public URL getImageUrl(String imageName) {
    // 创建OSSClient实例。
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    // 设置URL过期时间为1小时
    Date expiration = new Date(new Date().getTime() + 3600 * 1000);
    // 生成URL。
    URL url = ossClient.generatePresignedUrl(bucketName, imageName, expiration);
    // 关闭Client。
    ossClient.shutdown();
    return url;
  }

  public String getTest() {
    return test;
  }

  public String getEndpoint() {
    return endpoint;
  }

  public String getAccessKeyId() {
    return accessKeyId;
  }

  public String getAccessKeySecret() {
    return accessKeySecret;
  }

  public String getBucketName() {
    return bucketName;
  }

  public String getFirstkey() {
    return firstkey;
  }

  public String getUrlhead() {
    return urlhead;
  }
}
